package com.songtech.config;

import com.github.pagehelper.PageHelper;
import com.songtech.base.universal.dao.util.GetBaseResource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Configuration
@EnableTransactionManagement //开启注解事务管理，等同于xml配置文件中的 <tx:annotation-driven />
public class MyBatisConfig implements TransactionManagementConfigurer,EnvironmentAware{
	
	private Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);
	
	@Autowired 
	private DataSourceConfig dataSourceConfig;
	
	private RelaxedPropertyResolver propertyResolver;

	
	/**
	 * mybatis配置分页插件
	 * @return
	 */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSourceConfig.createDataSource());
        //分页插件 //
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("dialect", "mysql");
        pageHelper.setProperties(properties);
        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(this.getResource(resolver));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("装配sqlsessionFactory fail "+  e.getMessage());
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 加载mybatis资源文件
     * @param resolver
     * @return
     * @throws IOException
     */
    private Resource[] getResource(ResourcePatternResolver resolver) throws IOException{
    	List<Resource[]> list = new ArrayList<>();
    	list.add(resolver.getResources(propertyResolver.getProperty("mapperLocations")));
    	list.add(GetBaseResource.getResource(resolver));// 加载核心dao的资源文件
    	
    	ArrayList<Resource> al = new ArrayList<>();
    	for(Resource[] resource : list){
    		for(Resource r : resource){
    			al.add(r);
    		}
    	}
    	return al.toArray(new Resource[0]);
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
    /**
     * 事物
     */
    @Bean(name = "txManager")
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(dataSourceConfig.createDataSource());
	}

	@Override
	public void setEnvironment(Environment environment) {
		 this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
	}
}
